package com.xsmous.open.snappy;

import org.apache.commons.compress.utils.IOUtils;
import org.xerial.snappy.Snappy;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 雨一直夏灬
 * @since 2020/5/30 11:06 上午
 * 年少无为、码上为生
 */
public class SnappyDemo {
    public static void main(String[] args) {
        try {
            List<String> results = readFile();
            StringBuilder sb = new StringBuilder();
            results.forEach(sb::append);
            String content = sb.toString();
            System.out.printf("before snappy compress: %d\n", content.getBytes().length);

            // 压缩
            byte[] snappyCompressed = Snappy.compress(content);
            double ratio =  snappyCompressed.length / (double) content.length();
            System.out.printf("after snappy compress: %d, compress ratio: %f\n", snappyCompressed.length, ratio);

            // 解压
            byte[] uncompress = Snappy.uncompress(snappyCompressed);
            String unCompressContent = new String(uncompress);
            System.out.println(unCompressContent);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static List<String> readFile() throws IOException {
        List<String> list = new ArrayList<>();
        FileReader fileReader = new FileReader("/Users/xianmingliu/xsomnus/bigdata/datasets/pride-and-prejudice.txt");
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            list.add(line);
        }

        bufferedReader.close();
        fileReader.close();

        return list;
    }
}
